using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Net;
using System.Xml;
using System.IO;

public partial class taskdetails : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        TextBox1.Text=Request.QueryString["tid"];
        TextBox2.Text = Request.QueryString["userdn"];
        //get Task details
        XmlDocument taskrequestxml = new XmlDocument();
        taskrequestxml.LoadXml(Requests.getTaskRequestString());

        taskrequestxml.SelectSingleNode("//*[local-name()='TaskId']").InnerText = TextBox1.Text;
        taskrequestxml.SelectSingleNode("//*[local-name()='Target']").InnerText = TextBox2.Text;

        XmlDocument soapEnvelopeXml = CreateSoapEnvelope(taskrequestxml.InnerXml);
        String soapResult = CallWebService(soapEnvelopeXml);
        parseTaskXML(soapResult);

    }

    private void parseTaskXML(string soapResult)
    {
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.LoadXml(soapResult);
        XmlNode controls = xmldoc.SelectSingleNode("//*[local-name()='ApplicationData']/*[local-name()='forminputdata']/*[local-name()='freeformcontrols']");

        Label l = null;
        TextBox t = null;
        if (controls == null)
            return;
        controls = controls.FirstChild;
        while(controls !=null) 
        {
            if (controls is XmlElement)
            {
                l = new Label();
                l.ForeColor = System.Drawing.Color.Blue;
                l.Text = controls.Name;
                l.Height = 20;
                Panel4.Controls.Add(l);
                t = new TextBox();
                t.Height = 15;
                
                if (controls.HasChildNodes)
                {
                    t.Text = controls.FirstChild.InnerText;
                }
                Panel5.Controls.Add(t);
                if (l.Text.Equals("Status")||l.Text.Equals("dn"))
                {
                    l.Visible = false;
                    t.Visible = false;
                    l.Height = 0;
                    t.Height = 0;
                }
                else
                {
                    Panel4.Controls.Add(new LiteralControl("<br /><br />"));
                    Panel5.Controls.Add(new LiteralControl("<br /><br />"));
                }
            }
            controls = controls.NextSibling;
        }
    }

   /* private void RecurseXmlDocument(XmlNode root)
    {
        if (root is XmlElement)
        {
            Console.WriteLine(root.Name);
            if (root.HasChildNodes)
                RecurseXmlDocument(root.FirstChild);
            if (root.NextSibling != null)
                RecurseXmlDocument(root.NextSibling);
        }
        else if (root is XmlText)
        {
            string text = ((XmlText)root).Value;
            Console.WriteLine(text);
        }
        else if (root is XmlComment)
        {
            string text = root.Value;
            Console.WriteLine(text);
            if (root.HasChildNodes)
                RecurseXmlDocument(root.FirstChild);
            if (root.NextSibling != null)
                RecurseXmlDocument(root.NextSibling);
        }
    }*/

    public String CallWebService(XmlDocument soapEnvelopeXml)
    {
        String _url = "http://cin400332l/cordys/com.eibus.web.soap.Gateway.wcp?organization=o%3Daspinbox%2Ccn%3Dcordys%2Ccn%3Ddefinst%2Co%3Dvanenburg.com&messageOptions=0";
        String _action = "";


        HttpWebRequest webRequest = CreateWebRequest(_url, _action);
        InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);

        // begin async call to web request.
        IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);

        // suspend this thread until call is complete. You might want to
        // do something usefull here like update your UI.
        asyncResult.AsyncWaitHandle.WaitOne();

        // get the response from the completed web request.
        string soapResult;
        using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
        using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
        {
            soapResult = rd.ReadToEnd();
        }
        Console.Write(soapResult);
        return soapResult;

    }

    private static HttpWebRequest CreateWebRequest(string url, string action)
    {
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        webRequest.Credentials = CredentialCache.DefaultCredentials;
        webRequest.Accept = "*/*";
        webRequest.ContentType = "text/xml;charset=\"utf-8\"";
        webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
        webRequest.Referer = "http://cin400332l/cordys/wcp/library/system/framework.htm";
        webRequest.Method = "POST";
        return webRequest;
    }

    private static XmlDocument CreateSoapEnvelope(String requestXML)
    {
        XmlDocument soapEnvelop = new XmlDocument();
        soapEnvelop.LoadXml(requestXML);
        //soapEnvelop.LoadXml("<SOAP:Envelope xmlns:SOAP='http://schemas.xmlsoap.org/soap/envelope/'>	<SOAP:Header xmlns:SOAP='http://schemas.xmlsoap.org/soap/envelope/'>		<header xmlns='http://schemas.cordys.com/General/1.0/'>			<Logger xmlns='http://schemas.cordys.com/General/1.0/'></Logger></header>		<i18n:international xmlns:i18n='http://www.w3.org/2005/09/ws-i18n'><locale xmlns='http://www.w3.org/2005/09/ws-i18n'>en-us</locale></i18n:international></SOAP:Header><SOAP:Body>		<ExecuteProcess xmlns='http://schemas.cordys.com/bpm/execution/1.0'>			<type>definition</type>			<receiver>bpm/testbpm</receiver>			<message/>			<source>Run from Process Designer</source>		</ExecuteProcess>	</SOAP:Body></SOAP:Envelope>");
        return soapEnvelop;
    }

    private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
    {
        using (Stream stream = webRequest.GetRequestStream())
        {
            soapEnvelopeXml.Save(stream);
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        XmlDocument performtaskrequestxml = new XmlDocument();
        performtaskrequestxml.LoadXml(Requests.getperformTaskRequestString());

        XmlNode taskid = performtaskrequestxml.SelectSingleNode("//*[local-name()='TaskId']");
        taskid.InnerText = TextBox1.Text;

        XmlNode action = performtaskrequestxml.SelectSingleNode("//*[local-name()='Action']");
        action.InnerText = "COMPLETE";

        XmlNode appdataroot = performtaskrequestxml.SelectSingleNode("//*[local-name()='freeformcontrols']");

        Label l = null;
        TextBox t = null;
        IEnumerator ie= Panel5.Controls.GetEnumerator();
        foreach (Control c in Panel4.Controls)
        {
            if (c is Label)
            {
                l=(Label)c;
                XmlNode xnode=performtaskrequestxml.CreateElement(l.Text,"http://schemas.cordys.com/1.0/xforms/processapi");
                appdataroot.AppendChild(xnode);
                
            }
            
            if(ie.MoveNext()==true)
            {
            Control cc = (Control)ie.Current;
            if (cc is TextBox)
            {
                t=(TextBox)cc;
                appdataroot.LastChild.InnerText = t.Text;
                
            }
            }
        }

        XmlDocument soapEnvelopeXml = CreateSoapEnvelope(performtaskrequestxml.InnerXml);
        String soapResult = CallWebService(soapEnvelopeXml);
        //parseTaskXML(soapResult);
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        
        XmlDocument performtaskrequestxml = new XmlDocument();
        performtaskrequestxml.LoadXml(Requests.getperformTaskRequestString());

        XmlNode taskid = performtaskrequestxml.SelectSingleNode("//*[local-name()='TaskId']");
        taskid.InnerText = TextBox1.Text;

        XmlNode action = performtaskrequestxml.SelectSingleNode("//*[local-name()='Action']");
        action.InnerText = "COMPLETE";

        XmlNode appdataroot = performtaskrequestxml.SelectSingleNode("//*[local-name()='freeformcontrols']");

        Label l = null;
        TextBox t = null;
        IEnumerator ie = Panel5.Controls.GetEnumerator();
        foreach (Control c in Panel4.Controls)
        {
            if (c is Label)
            {
                l = (Label)c;
                XmlNode xnode = performtaskrequestxml.CreateElement(l.Text, "http://schemas.cordys.com/1.0/xforms/processapi");
                appdataroot.AppendChild(xnode);

            }
            if (ie.MoveNext() == true)
            {
                Control cc = (Control)ie.Current;
                if (cc is TextBox)
                {
                    t = (TextBox)cc;
                    if (l.Text.Equals("Status"))
                    {
                        appdataroot.LastChild.InnerText = "Reject";
                    }
                    else
                    {
                        t = (TextBox)cc;
                        appdataroot.LastChild.InnerText = t.Text;
                    }

                }
            }
            
        }

        XmlDocument soapEnvelopeXml = CreateSoapEnvelope(performtaskrequestxml.InnerXml);
        String soapResult = CallWebService(soapEnvelopeXml);
        //parseTaskXML(soapResult);
    }
}
